/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.serializer;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.dailydev.wave.robot.RobotException;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.impl.ElementSerializer;
import com.google.wave.api.impl.EventDataSerializer;
import com.google.wave.api.impl.EventMessageBundle;
import com.google.wave.api.impl.EventMessageBundleSerializer;
import com.google.wave.api.impl.OperationSerializer;
import com.google.wave.api.impl.RobotMessageBundleImpl;
import com.metaparadigm.jsonrpc.JSONSerializer;
import com.metaparadigm.jsonrpc.MarshallException;
import com.metaparadigm.jsonrpc.SerializerState;
import com.metaparadigm.jsonrpc.UnmarshallException;

/**
 * @author Roman Bosak, DailyDev.org
 */
public class RobotMessageBundleSerializer implements ISerializer<RobotMessageBundle> {

    private static Logger logger = Logger.getLogger(RobotMessageBundleSerializer.class.getName());

    private JSONSerializer serializer;

    /**
     * 
     */
    public RobotMessageBundleSerializer() {
        try {
            serializer = new JSONSerializer();
            serializer.registerDefaultSerializers();
            serializer.registerSerializer(new EventMessageBundleSerializer());
            serializer.registerSerializer(new EventDataSerializer());
            serializer.registerSerializer(new ElementSerializer());
            serializer.registerSerializer(new OperationSerializer());
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Unable to initialize serializers", e);
        }
    }

    /**
     * Deserializes JSON representation of body of robot's request to the
     * {@link RobotMessageBundleImpl} structures.
     * 
     * @param json
     *            JSON representation of body of robot's request
     * @return {@link RobotMessageBundleImpl} instance filled by data parsed
     *         from the <code>json</code> parameter.
     * @throws RobotException
     *             If there is a syntax error in the source JSON string or a
     *             duplicated key, or if there is a problem in mapping of JSON
     *             stored to object to {@link EventMessageBundle}. The reason
     *             can be recognized from exception embedded by
     *             {@link RobotException}.
     */
    public RobotMessageBundle deserialize(String json) throws RobotException {
        try {
            JSONObject jsonObject = new JSONObject(json);
            EventMessageBundle bundle = (EventMessageBundle) serializer.unmarshall(new SerializerState(),
                    EventMessageBundle.class, jsonObject);
            return new RobotMessageBundleImpl(bundle, "Habla");
        } catch (JSONException jsonx) {
            throw new RobotException("Unable to parse request data to JSON object", jsonx);
        } catch (UnmarshallException e) {
            throw new RobotException("Unable to parse request data to JSON object", e);
        }
    }

    /**
     * @param operations
     * @param response
     * 
     * @throws RobotException
     */
    public String serialize(RobotMessageBundle toSerialize) throws RobotException {
        try {
            return serializer.toJSON(toSerialize);
        } catch (MarshallException e) {
            throw new RobotException("Unable to marshal JSON object into JSON String", e);
        }
    }
}
